/**
 * 
 */
package com.zte.claa.inficombo.csa.app.comm.csif.mina;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zte.claa.inficombo.csa.app.comm.csif.CSIFCommService;
import com.zte.claa.inficombo.csa.app.comm.csif.CSIFMessageBuilder;
import com.zte.claa.inficombo.csa.app.comm.csif.mina.msg.CSIFMessage;

/**
 * @author lyp
 *
 */
public class CSIFMinaClientHandler extends IoHandlerAdapter {
	private  Logger logger = LoggerFactory.getLogger(CSIFMinaClientHandler.class);
	
	private CSIFCommService csifCommSvr = null;

	public CSIFMinaClientHandler(CSIFCommService iotmCommSvr) {
		this.csifCommSvr = iotmCommSvr;
	}

	@Override
	public void sessionCreated(IoSession session) throws Exception {
		logger.info("session created: " + session.getId());
		super.sessionCreated(session);
	}

	@Override
	public void sessionOpened(IoSession session) throws Exception {
		logger.info("session opened: " + session.getId());
		super.sessionOpened(session);
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		logger.info("session closed: " + session.getId()+", remoteAddr="+session.getRemoteAddress());
		if(this.csifCommSvr != null){
			this.csifCommSvr.reportConnectStatus(CSIFCommService.CONN_STATUS_CLOSE);
		}
		super.sessionClosed(session);
	}

	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		logger.info("session idled: " + session.getId());
		if(this.csifCommSvr != null){
			this.csifCommSvr.reportConnectStatus(CSIFCommService.CONN_STATUS_IDLE);
		}
		super.sessionIdle(session, status);
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		logger.error("exception: " + cause.getMessage()+", remoteAddr="+session.getRemoteAddress(), cause);
		if(this.csifCommSvr != null){
			this.csifCommSvr.reportException(cause);
		}
		super.exceptionCaught(session, cause);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		logger.debug("session message received: " + session.getId()+ ", msg: " + message);
		if(this.csifCommSvr != null){	
			String jsonMsg = CSIFMessageBuilder.parseMessage((CSIFMessage)message);
			this.csifCommSvr.reportMessage(jsonMsg);
		}
	}

	@Override
	public void messageSent(IoSession session, Object message) throws Exception {
		logger.debug("session message sent: "+session.getId()+", msg: "+message.toString());
	}

	public void inputClosed(IoSession session) throws Exception {
		logger.info("session = "+session.getId()+": inputClosed! "+", remoteAddr="+session.getRemoteAddress());
		// 避免死循环触发inputClosed()方法。
		// session.close(true);
		session.closeNow();
		super.inputClosed(session);
	}
}
